﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Rung.Common;
using Rung.EBook.UI.Controls.Panels;

namespace Rung.EBook.UI.Forms
{
    public partial class ConfigForm : Form
    {
        public const string JOBS_FILE_PATH = "rules";
        public const string JOBS_FILE_NAME = "TextAnalizerRules.dat";
        internal static Dictionary<string, pnTextAnalizer.TextAnalizer> Analizers;
        private pnTextAnalizer pnTextAnalizer;

        static ConfigForm()
        {
            LoadAnalizers();
        }

        internal static void LoadAnalizers()
        {
            ConfigForm.Analizers = new Dictionary<string, pnTextAnalizer.TextAnalizer>();

            string fullName = Rung.EBook.Common.Driver.StaticFunctions.GetTextAnalizerRulesFilePath();
            if (File.Exists(fullName))
            {
                ConfigForm.Analizers = SerializeHelper.DeSerialize<Dictionary<string, pnTextAnalizer.TextAnalizer>>(fullName);
            }
            else
            {
            }
        }

        private ConfigForm()
        {
            InitializeComponent();
        }

        public ConfigForm(pnTextAnalizer pnTextAnalizer)
            : this()
        {
            this.pnTextAnalizer = pnTextAnalizer;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string name = txbName.Text.Trim();
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("请填写规则名称。");
            }
            else
            {
                if (ConfigForm.Analizers.ContainsKey(name))
                {
                    if (MessageBox.Show("已存在该名称的规则，是否覆盖？", "警告", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        ConfigForm.Analizers.Remove(name);
                    else
                        return;
                }

                this.pnTextAnalizer.currentTA = this.pnTextAnalizer.currentTA.Clone();
                this.pnTextAnalizer.currentTA.Name = name;
                ConfigForm.Analizers.Add(name, this.pnTextAnalizer.currentTA);

                string fullName = Rung.EBook.Common.Driver.StaticFunctions.GetTextAnalizerRulesFilePath();
                SerializeHelper.Serialize(ConfigForm.Analizers, fullName);

                MessageBox.Show("保存成功。");
                this.pnTextAnalizer.tsm载入已存方案_Refresh();
                this.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
